<template>
  <view class="py-2">
    <u-upload
      :name="name"
      :accept="accept"
      :width="width"
      :height="height"
      :multiple="multiple"
      :maxCount="maxCount"
      :uploadText="tips"
      :maxSize="maxSize * 1024 * 1024"
      :fileList="fileList"
      :disabled="disabled"
      :deletable="!disabled"
      @afterRead="afterRead"
      @delete="deleteFile">
    </u-upload>
    <view v-if="bottomTips && !disabled" class="u-info-disabled fz-12">
      {{ bottomTips }}
    </view>
  </view>
</template>

<script setup lang="ts">
import { upFile } from "@/api/upFile";

const props = defineProps({
  // 上传组件name,保持唯一性
  name: {
    type: String,
    required: true,
    default: 'uploadName'
  },
  // 上传类型
  accept: {
    type: String,
    default: 'image'
  },
  width: {
    type: Number,
    default: 100
  },
  height: {
    type: Number,
    default: 100
  },
  // 是否多选
  multiple: {
    type: Boolean,
    default: false
  },
  // 最大选择图片的数量
  maxCount: {
    type: [String, Number],
    default: 1
  },
  // 上传大小限制 M
  maxSize: {
    type: Number,
    default: 10
  },
  tips: {
    type: String,
    default: '上传照片'
  },
  // 只支持.jpg.png 格式，400*400尺寸
  bottomTips: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 绑定值 多张为[url,url]
  modelValue: {
    type: [String, Array]
  }
})

function isNetworkUrl(url: string) {
  try {
    const urlObj = new URL(url);
    const protocol = urlObj.protocol.toLowerCase();
    return protocol === 'http:' || protocol === 'https:';
  } catch (e) {
    // 如果URL解析失败，返回false
    return false;
  }
}

interface FileItemTypes {
  url: string;
  name?: string;
  status: 'uploading' | 'success' | '';
  message?: string;
}

const fileList = ref<FileItemTypes[]>([]);
const afterRead = async (event: any) => {
  //  当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  const uploadedList = props.multiple ? event.file : [event.file];
  uploadedList.forEach((v: any) => {
    fileList.value.push({
      url: v.url,
      name: v.name,
      status: isNetworkUrl(v.url) ? 'success' : 'uploading',
      message: '上传中'
    })
  });

  for (let i = 0; i < uploadedList.length; i++) {
    const data = await upFile(uploadedList[i]);
    // 上传成功后,替换上传列表中的临时路径已经更改上传状态
    const currentIndex = fileList.value.findIndex(v=> v.name === uploadedList[i].name);
    fileList.value[currentIndex].url = data.url;
    fileList.value[currentIndex].status = 'success';
    fileList.value[currentIndex].message = '';
  }
  upDate(); // 更新绑定值
};

// 删除文件
const deleteFile = (event: {index: number}) => {
  fileList.value.splice(event.index, 1);
  upDate(); // 更新绑定值
};

const emits = defineEmits(['update:modelValue']);
const upDate = () => {
  const successList = unref(fileList).filter(v=> v.status === 'success');
  const urls = successList.map(v=> v.url);
  emits('update:modelValue', props.multiple ? urls : (urls.length ? urls[urls.length - 1] : ''));
};

// 监听绑定值,回显
watch(
    () => props.modelValue,
    (newVal) => {
      const urls = props.multiple ? newVal : (!!newVal ? [newVal] : []);

      fileList.value = (urls as string[]).map((url: string)=>{
        return {
          url: url,
          status: props.disabled ? '' : 'success',
          message: ''
        }
      })
    },
    {
      immediate: true
    }
);
</script>

<style lang="scss" scoped></style>